Grokking Tree Coding Patterns for Interviews
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Course Overview
Introduction to Tree
Types of Tree
BST Traversal Techniques
BST Operations
Introduction to Level Order Traversal Pattern
Reverse Level Order Traversal (easy)
Solution: Reverse Level Order Traversal
Find Largest Value in Each Tree Row (medium)
Solution: Find Largest Value in Each Tree Row
Maximum Width of Binary Tree (medium)
Solution: Maximum Width of Binary Tree
Maximum Level Sum of a Binary Tree (medium)
Solution: Maximum Level Sum of a Binary Tree
Zigzag Traversal (medium)
Solution: Zigzag Traversal
Even Odd Tree (medium)
Solution: Even Odd Tree
N-ary Tree Level Order Traversal (hard)
Solution: N-ary Tree Level Order Traversal
Introduction to Tree Depth Pattern
Maximum Depth (or Height) of Binary Tree (easy)
Solution: Maximum Depth (or Height) of Binary Tree
Minimum Depth of a Binary Tree (easy)
Solution: Minimum Depth of a Binary Tree
Balanced Binary Tree (easy)
Solution: Balanced Binary Tree
Tree Diameter (easy)
Solution: Tree Diameter
Maximum Depth of N-ary Tree (easy)
Solution: Maximum Depth of N-ary Tree
Find maximum depth of subtree (medium)
Solution: Find maximum depth of subtree
Root to Leaf Path Pattern (medium)
Introduction to Root to Leaf Path Pattern
Binary Tree Paths (easy)
Solution: Binary Tree Paths
Sum of Root To Leaf Binary Numbers (easy)
Solution: Sum of Root To Leaf Binary Numbers
Insufficient Nodes in Root to Leaf Paths (medium)
Solution: Insufficient Nodes in Root to Leaf Paths
Smallest String Starting From Leaf (medium)
Solution: Smallest String Starting From Leaf
Pseudo-Palindromic Paths in a Binary Tree (medium)
Solution: Pseudo-Palindromic Paths in a Binary Tree
All Paths for a Sum (medium)
Solution: All Paths for a Sum
Sum of Path Numbers (medium)
Solution: Sum of Path Numbers
Path With Given Sequence (medium)
Solution: Path With Given Sequence
Count Paths for a Sum (medium)
Solution: Count Paths for a Sum
Leaf Processing Pattern (medium)
Introduction to Leaf Processing Pattern
Sum of Left Leaves (easy)
Solution: Sum of Left Leaves
Leaf-Similar Trees (easy)
Solution: Leaf-Similar Trees
Check if all leaves are at same level (medium)
Solution: Check if all leaves are at same level
Delete Leaves With a Given Value (medium)
Solution: Delete Leaves With a Given Value
Deepest Leaves Sum (medium)
Solution: Deepest Leaves Sum
Tree View Pattern (medium)
Introduction to Tree View Pattern
Right View of a Binary Tree (medium)
Solution: Right View of a Binary Tree
Top View Of the Binary Tree (medium)
Solution: Top View Of the Binary Tree
Bottom View Of the Binary Tree (medium)
Solution: Bottom View Of the Binary Tree
Boundary of Binary Tree (medium)
Solution: Boundary of Binary Tree
Introduction to Comparison of Two Trees Pattern
Symmetric Tree (easy)
Solution: Symmetric Tree
Mirror Image Trees (medium)
Solution: Mirror Image Trees
Subtree of Another Tree (easy)
Solution: Subtree of Another Tree
Isomorphic Trees (medium)
Solution: Isomorphic Trees
Introduction to Serialize and Deserialize Tree Pattern
Serialize and Deserialize BST (medium)
Solution: Serialize and Deserialize BST
Verify Preorder Serialization of a Binary Tree (medium)
Solution: Verify Preorder Serialization of a Binary Tree
Create Binary Tree From Descriptions (medium)
Solution: Create Binary Tree From Descriptions
Serialize and Deserialize N-ary Tree (hard)
Solution: Serialize and Deserialize N-ary Tree
Solution: Boundary of Binary Tree

Problem Statement

The boundary of the tree is the concatenation of the root, the left boundary, the leaf nodes in left to right order, and the right boundary in the reverse order.

  • The left boundary includes all the nodes on the leftmost path from the root, excluding the leftmost leaf.
  • The leaf nodes include all nodes that do not have any children, traversed from left to right.
  • The right boundary includes all nodes on the rightmost path, excluding the rightmost leaf, but they are recorded in reverse order. Return the values of these boundary nodes in order.

Given the root of a binary tree, return an array containing the values of its boundary.

Examples

Example 1:

  • Input: root = [1, null, 5, 2, 4]
Image
  • Expected Output: [1, 2, 4, 5]
  • Justification: The left boundary is empty, 1 is root node, the leaves are 2 and 4, and the right boundary in reverse is 5.

Example 2:

  • Input: root = [1, 2, 3, 4, 5, 6, 7, null, null, 9]
Image
  • Expected Output: [1,2,4,9,6,7,3]
  • Justification: The left boundary is 1 → 2, the leaves are 4, 9, 6, and 7, and the right boundary in reverse is 3.

Example 3:

  • Input: root = [1, 2, null, 3, 4]
Image
  • Expected Output: [1, 2, 3, 4]
  • Justification: The left boundary is 1 → 2, the leaves are 3 and 4, and the right boundary is empty.

Constraints:

  • The number of nodes in the tree is in the range [1, 104].
  • -1000 <= Node.val <= 1000

Solution

To solve this problem, we need to traverse the binary tree and collect the nodes that form the boundary. The traversal is divided into three parts: collecting the left boundary, identifying the leaf nodes, and finally collecting the right boundary in reverse order. The challenge lies in ensuring that we don't mistakenly add leaf nodes twice when they are part of the left or right boundary. To manage this, we first focus on gathering the left boundary, then the leaf nodes, and finally the right boundary separately.

This approach works efficiently because it ensures we visit each node exactly once and correctly identify which part of the boundary it belongs to. By dividing the problem into these three tasks, we can ensure a well-organized and accurate traversal of the tree.

Step-by-Step Algorithm

  1. Check if the root is null:

    • If the root is null, return an empty result list because there is no boundary to collect.
  2. Add the root to the result list:

    • If the root is not a leaf (it has at least one child), add the root’s value to the result list.
  3. Collect the left boundary using BFS:

    • Initialize a queue and add the left child of the root to it.
    • While the queue is not empty, do the following:
      • Poll the front node from the queue.
      • If the node is not a leaf (it has at least one child), add its value to the result list.
      • If the node has a left child, add it to the queue. Otherwise, if it has a right child, add that to the queue. This ensures that we only collect the nodes that are part of the left boundary.
  4. Collect the leaf nodes:

    • Recursively traverse the tree from the root:
      • For each node, check if it is a leaf (it has no children). If it is, add its value to the result list.
      • If the node is not a leaf, recursively traverse its left and right children, continuing to search for leaves.
  5. Collect the right boundary using BFS:

    • Initialize a stack and add the right child of the root to it.
    • While the stack is not empty, do the following:
      • Poll the front node from the queue.
      • If the node is not a leaf (it has at least one child), push its value onto the stack.
      • If the node has a right child, add it to the queue. Otherwise, if it has a left child, add that to the queue. This ensures that we only collect the nodes that are part of the right boundary.
    • Once the BFS is complete, pop the elements from the stack and add them to the result list to ensure the right boundary is added in reverse order.
  6. Return the final result list:

    • After collecting the root, left boundary, leaf nodes, and right boundary, return the result list containing the boundary nodes.

Algorithm Walkthrough

Input Tree Structure:

The binary tree for the given input looks like this:

        1
      /   \
     2     3
    / \   / \
   4   5 6   7
      /
     9

Steps:

  1. Step 1 - Check if the tree is empty:

    • The root is not null, so we proceed with the boundary collection process.
  2. Step 2 - Add the root node to the result list:

    • The root node is 1, and since it's not a leaf (it has both left and right children), we add 1 to the result list.
    • Current result = [1].
  3. Step 3 - Collect the left boundary using BFS:

    • We start collecting the left boundary nodes by performing a BFS traversal starting from the left child of the root (root.left = 2).

    • Iteration 1:

      • The node we are processing is 2. It's not a leaf, so we add it to the result list.
      • Add its left child (4) to the queue.
      • result = [1, 2].
    • Iteration 2:

      • The node we are processing is 4. Since 4 is a leaf (no left or right children), we stop collecting further left boundary nodes.
      • Note: Although node 4 is part of the left boundary, it will be handled later during leaf collection.
    • Left boundary collection is complete.

  4. Step 4 - Collect the leaf nodes:

    • Now, we need to collect all the leaf nodes of the tree. We perform a DFS traversal and collect leaf nodes from both the left and right subtrees of the root.

    • Traversing the left subtree:

      • Start from the left child of the root (root.left = 2).

      • Node 2:

        • Node 2 is not a leaf, so we recurse to its children.

        • Node 4:

          • Node 4 is a leaf (no left or right children). Add 4 to the result list.
          • result = [1, 2, 4].
        • Node 5:

          • Node 5 is not a leaf, so we recurse to its left child.

          • Node 9:

            • Node 9 is a leaf (no left or right children). Add 9 to the result list.
            • result = [1, 2, 4, 9].
    • Traversing the right subtree:

      • Now, we traverse the right subtree of the root (root.right = 3).

      • Node 3:

        • Node 3 is not a leaf, so we recurse to its children.

        • Node 6:

          • Node 6 is a leaf (no left or right children). Add 6 to the result list.
          • result = [1, 2, 4, 9, 6].
        • Node 7:

          • Node 7 is a leaf (no left or right children). Add 7 to the result list.
          • result = [1, 2, 4, 9, 6, 7].
    • Leaf collection is complete.

  5. Step 5 - Collect the right boundary using BFS:

    • Finally, we collect the right boundary nodes. We perform a BFS traversal starting from the right child of the root (root.right = 3), but we collect the nodes in reverse order.

    • Iteration 1:

      • The node we are processing is 3. It's not a leaf, so we push 3 onto the stack.
      • Add its right child (7) to the queue. Since 7 is a leaf, it is not processed further as part of the right boundary.
      • Stack after this iteration: stack = [3].
    • Right boundary collection is complete. We now pop the elements from the stack (to reverse the order) and add them to the result list.

      • Pop 3 from the stack and add it to the result.
      • result = [1, 2, 4, 9, 6, 7, 3].
  6. Step 6 - Return the final result:

    • After collecting the root, left boundary, leaf nodes, and right boundary, the final result is:
    • Final Output: [1, 2, 4, 9, 6, 7, 3].

Final Explanation:

  • Left boundary: Nodes 1 → 2 are part of the left boundary.
  • Leaf nodes: The leaf nodes are 4, 9, 6, and 7.
  • Right boundary: The right boundary is node 3, and it is added to the result in reverse order.

Thus, the boundary of the tree for the given input is [1, 2, 4, 9, 6, 7, 3].

Code

Java
Saved to Cloud

. . . .

Complexity Analysis

Time Complexity

  • Left Boundary Traversal: The addLeftBoundaryBFS() method traverses the left side of the tree, visiting each node once. The time complexity of this traversal is , where h is the height of the tree.
  • Leaf Collection: The addLeaves() function performs a full tree traversal to collect all the leaves. This takes , where n is the number of nodes in the tree.
  • Right Boundary Traversal: The addRightBoundaryBFS() function traverses the right side of the tree and uses a stack to reverse the right boundary nodes. The time complexity for this traversal is as it visits the right boundary nodes and reverses them.

The overall time complexity is the sum of the three traversals, which is (since in the worst case, every node is visited once).

Space Complexity:

  • Queue/Stack Usage: Both BFS traversals use a queue and a stack, with at most space being used at any point, where h is the height of the tree.
  • Recursion for Leaves: The addLeaves() function is a recursive function, so the recursion stack will have a space complexity of .
  • Result List: The result list will store all the boundary nodes, which in the worst case is .

Thus, the overall space complexity is , where n is the number of nodes in the tree.

Boundary of Binary Tree (medium)
Introduction to Comparison of Two Trees Pattern
Mark as Completed

On this page

Problem Statement

Examples

Solution

Step-by-Step Algorithm

Algorithm Walkthrough

Final Explanation:

Code

Complexity Analysis

Time Complexity

Space Complexity: